<!--  -->
<template>
    <view class="container">
        <u-subsection :list="list" :current="current" button-color="#07c061" height="80"
            active-color="#fff" @change="change"></u-subsection>
        <template v-if="current == 0">
            <live></live>
        </template>
        <template v-if="current == 1">
            <product ref="product" :list="newList" :status="status" @chooseDate="chooseDate"></product>
        </template>
        <template v-if="current == 2">
            <records></records>
        </template>
    </view>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import live from './live.vue';
import product from './product.vue';
import records from './records.vue';



export default {
    //import引入的组件需要注入到对象中才能使用
    components: {
        live,
        product,
        records
    },
    data() {
        //这里存放数据
        return {
            list: [{name: '直播视频'}, {name: '商品'}, {name: '跟团记录',}],
            current: 1,
			
			weChatCode:'',
			userToken:uni.getStorageSync('X-Access-Token'),
			
			form:{
				pageNum:1,
				pageSize:10,
				day:'',
			},
			status:'nomore',
			last_page:1,
			newList:[],
			
			// 定义轮询的间隔时间
			interval:3000,
			intervalID:'',
			
			
        };
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
	
	onReachBottom(){
		let  that = this;
		if(that.current == 1){
			if(this.form.pageNum < this.last_page){
				this.status = 'loading';
				that.form.pageNum++;
				that.getList();
			}else{
				this.status = 'nomore'
			}
		}
	},
	
	//监听页面隐藏
	onHide(){
		clearInterval(this.intervalID);
	},
	
	// 监听页面卸载
	onUnload(e){
		clearInterval(this.intervalID);
	},
	
	onShow() {
		let  that = this
		that.form.day = that.getNext15Days()[0].date
		if(!that.userToken){
			that.getToken();
		}else{
			that.getList();
			
			that.intervalID = setInterval(function() {
			  that.getNewData();
			}, that.interval);
			
		}
	},
	
	
	onLoad() {
		let  that = this;
		//that.getToken();
		// that.bind();
	},
	
    methods: {
        change(index) {
            this.current = index;
        },
		
		
		// 监听团购数据
		getNewData(){
			let  that = this;
			let  obj  = {day:that.form.day}
			that.$u.api.checkGroupBuyData(obj).then(ret => {
				if(ret.code == 0){
					let list =ret.data;
					list.forEach((v)=>{
						that.newList.forEach((k)=>{
							if(v.goodsId == v.goodsId){
								k.price_t = v.price;
								k.count_t = v.count;
							}
						})
					})
				}else{
					clearInterval(this.intervalID);
				}
			})
		},
		
		// 切换日期
		chooseDate(v){
			console.log(v)
			let  that = this;
			if(v){
				that.form.day = v.date.date
				that.form.pageNum = 1;
				that.getList();
				
				clearInterval(this.intervalID);
				that.intervalID = setInterval(function() {
				  that.getNewData();
				}, that.interval);
			}
		},
		
		
		// 获取商品列表数据
		getList(){
			let  that = this;
			if(that.form.pageNum == 1){that.newList = []}
			that.$u.api.getOrderPlans(that.form).then(ret => {

				if(ret.code == 0){
					if(ret.data.total > 0){
						let res = ret.data;
						res.rows.forEach((v)=>{
							v.num = 0;
							v.price_t ='';
							v.count_t ='';
						})
						that.newList = res.rows ?  that.newList.concat(res.rows) : [];
						if(res.rows){
							that.last_page = res.pages;
							if(that.form.pageNum < that.pages){
								that.status = 'loading'
							}else{
								that.status = 'nomore'
							}
						}else{
							that.status = 'nomore'
						}
					}
					
					//  获取一下购物车数据
					that.getCartData();
					//   获取一下团购数据
					that.getNewData();
					
				}
			})
		},
		
		// 购物车数据
		getCartData(){
			let  that = this;
			that.$u.api.getCartData().then(ret => {
				if(ret.code == 0){
					if(ret.data&&ret.data.length){
						
						uni.setTabBarBadge({
							index:1,
							text:JSON.stringify(ret.data.length*1)
						})
						
						let list = ret.data;
						let shopList = that.newList;
						list.forEach((v)=>{
							if(v.day == that.form.day && v.status == 1){
								shopList.forEach((k)=>{
									if(k.goodsId == v.goods_id){
										k.num = v.num
									}
								})
							}
						})
					}else{
						uni.removeTabBarBadge({index:1})
					}
					//  更新一下 总计 延时一下
					setTimeout(()=>{
						that.$refs.product.sumFun();
					},500)
				}
			})
		},
		
		
		getToken(){
			let   that = this;
			uni.login({
				"provider": "weixin",
				"onlyAuthorize": true, // 微信登录仅请求授权认证
				success: function(event){
					const {code} = event
					//客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
					console.log(event)
					that.weChatCode = event.code;
					// that.weChatCode = 5;
					
					that.$u.api.getToken({weChatCode:that.weChatCode}).then(res => {
						console.log(res.code);
						if(res.code == 500){
							that.bind();
						}else{
							uni.setStorageSync('X-Access-Token',res.data)
							that.getList();
						}
					}) 
					
				},
				fail: function (err) {
			        // 登录授权失败  
			        // err.code是错误码
			    }
			})
		},
		
		getNext15Days() {
		  const result = [];
		  const today = new Date();
		  
		  for (let i = 0; i < 15; i++) {
		    const nextDay = new Date(today);
		    nextDay.setDate(today.getDate() + i);
		    
		    const day = nextDay.getDate();
		    const month = nextDay.getMonth() + 1;
		    const year = nextDay.getFullYear();
		    
		    const dayOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][nextDay.getDay()];
		    
		    const formattedDate = `${year}-${month < 10 ? '0' : ''}${month}-${day < 10 ? '0' : ''}${day}`;
		    
		    result.push({ date: formattedDate, dayOfWeek, day:day});
		  }
		  
		  return result;
		},
		
		
		bind(){
			let  that = this;
			uni.showModal({
				title: '温馨提示',
				content: '请您先绑定用户信息',
				success: function (res) {
					if (res.confirm) {
						that.onJump('/pages/home/binding',1)
					} 
				}
			});
		},
		
		onJump(url,t){
			switch (t){
				case 1:
					// 保留当前页面，跳转到应用内的某个页面
					uni.navigateTo({url:url})
					break;
				case 2:
					// 关闭当前页面，跳转到应用内的某个页面。
					uni.redirectTo({url:url})
					break;	
				case 3:
					// 关闭所有页面，打开到应用内的某个页面。
					uni.reLaunch({url:url})
					break;
				case 4:
					// 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面。
					uni.switchTab({url:url})
					break;	
			}
		},  
		
		
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {

    },
    beforeCreate() { }, //生命周期 - 创建之前
    beforeMount() { }, //生命周期 - 挂载之前
    beforeUpdate() { }, //生命周期 - 更新之前
    updated() { }, //生命周期 - 更新之后
    beforeDestroy() { }, //生命周期 - 销毁之前
    destroyed() { }, //生命周期 - 销毁完成
    activated() { }, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped>
.container{
    background-color: #eeeeef;
    height: 100vh;
}
</style>